using System;
using System.Linq.Expressions;
using Magiq.Support;
using Magiq.Tests.Support;
using NUnit.Framework;

namespace Magiq.Tests {
  [TestFixture]
  public class ExpressionExtenssionTests {
    private class Model {
      public string Prop { get; set; }
    }

    [Test]
    public void ShouldRetrieveNullIfPreviousExpressionChainDoesntExist() {
      Expression<Func<Model, string>> lambda = x => x.Prop;
      lambda.PreviousExpressionChain().Should(Be.Null);
    }

    [Test]
    public void ShouldRetrievePreviousExpressionChain() {
      Expression<Func<Model, int>> lambda = x => x.Prop.Length;
      var previousChain = lambda.PreviousExpressionChain();

      var compiled = previousChain.Compile();

      var model = new Model
                    {
                      Prop = "lala"
                    };
      compiled.DynamicInvoke(model).Should(Be.EqualTo("lala"));
    }

    [Test]
    public void ShouldRetrieveRootIfPreviousExpressionChainIsRootAndIncludesRoot() {
      Expression<Func<Model, string>> lambda = x => x.Prop;
      var previousChain = lambda.PreviousExpressionChain(true);
      var compiled = previousChain.Compile();
      var model = new Model
                    {
                      Prop = "lala"
                    };

      compiled.DynamicInvoke(model).Should(Be.EqualTo(model));
    }
  }
}